package com.htfyun.guowenagingscreen;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.PixelFormat;
import android.os.Build;
import android.os.IBinder;
import android.view.GestureDetector;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.LinearLayout;


/**
 * Created by sst on 2018/5/30.
 */

public class FTFloatWindowService extends Service implements View.OnTouchListener {

    LinearLayout mFloatLayout = null;
    WindowManager.LayoutParams wmParams;
    WindowManager mWindowManager;
    Button btnFactory;

    private Context context;

    //触摸监听器
    GestureDetector mGestureDetector;

    @Override
    public void onCreate() {
        // TODO Auto-generated method stub
        super.onCreate();
        context = this;
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        addFloatView();

        return START_STICKY;
    }

    @Override
    public void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();

        removeFloatView();
    }


    private void removeFloatView() {
        if (mFloatLayout != null) {
            //移除悬浮窗口
            mWindowManager.removeView(mFloatLayout);

            btnFactory.setOnClickListener(null);
            btnFactory.setOnTouchListener(null);

            mFloatLayout = null;
        }
    }

    private void addFloatView() {

        if (mFloatLayout != null) {
            return;
        }

        wmParams = new WindowManager.LayoutParams();
        //获取的是WindowManagerImpl.CompatModeWrapper
        mWindowManager = (WindowManager) getApplication().getSystemService(getApplication().WINDOW_SERVICE);
        //设置window type
        if (Build.VERSION.SDK_INT >= 24) { /*android7.0不能用TYPE_TOAST*/
            wmParams.type = WindowManager.LayoutParams.TYPE_PHONE;
        } else { /*以下代码块使得android6.0之后的用户不必再去手动开启悬浮窗权限*/
            String packname = context.getPackageName();
            PackageManager pm = context.getPackageManager();
            boolean permission = (PackageManager.PERMISSION_GRANTED == pm.checkPermission("android.permission.SYSTEM_ALERT_WINDOW", packname));
            if (permission) {
                wmParams.type = WindowManager.LayoutParams.TYPE_PHONE;
            } else {
                wmParams.type = WindowManager.LayoutParams.TYPE_TOAST;
            }
        }

        wmParams.setTitle("FT-FloatWindow");
        //设置图片格式，效果为背景透明
        wmParams.format = PixelFormat.RGBA_8888;
        //设置浮动窗口不可聚焦（实现操作除浮动窗口外的其他可见窗口的操作）
        wmParams.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
        //调整悬浮窗显示的停靠位置为左侧置顶
        wmParams.gravity = Gravity.END | Gravity.BOTTOM;
        // 以屏幕左上角为原点，设置x、y初始值，相对于gravity
        wmParams.x = 200;
        wmParams.y = 300;

        //设置悬浮窗口长宽数据
        wmParams.width = WindowManager.LayoutParams.WRAP_CONTENT;
        wmParams.height = WindowManager.LayoutParams.WRAP_CONTENT;

         /*// 设置悬浮窗口长宽数据
        wmParams.width = 200;
        wmParams.height = 80;*/

        LayoutInflater inflater = LayoutInflater.from(getApplication());
        //获取浮动窗口视图所在布局
        mFloatLayout = (LinearLayout) inflater.inflate(R.layout.float_layout, null);
        //添加mFloatLayout
        mWindowManager.addView(mFloatLayout, wmParams);
        //浮动窗口按钮
        btnFactory = (Button) mFloatLayout.findViewById(R.id.btnFactory);

        mFloatLayout.measure(View.MeasureSpec.makeMeasureSpec(0,
                View.MeasureSpec.UNSPECIFIED), View.MeasureSpec
                .makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));

        btnFactory.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                FTUtils.startMainActivity(context);
            }
        });

        long startTime = EinkAgingScreenSharedPref.getStartTime_ms(this);
        long exitTime = EinkAgingScreenSharedPref.getExitTime_ms(this);
        String time = TimeStringUtils.makeTimeString(this, (exitTime - startTime) / 1000);
        btnFactory.setText(getString(R.string.float_factory_test_with_time, time));

        mGestureDetector = new GestureDetector(this, new MyOnGestureListener());
        btnFactory.setOnTouchListener(this);
    }


    @Override
    public boolean onTouch(View v, MotionEvent event) {
        if (mFloatLayout == null) {
            return false;
        }
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                isMove = false;
                mTouchStartX = (int) event.getRawX();
                mTouchStartY = (int) event.getRawY();
                mStartX = wmParams.x;//(int)event.getX();
                mStartY = wmParams.y;//(int)event.getY();
                break;

            case MotionEvent.ACTION_MOVE:

                mTouchCurrentX = (int) event.getRawX();
                mTouchCurrentY = (int) event.getRawY();
                wmParams.x += mTouchCurrentX - mTouchStartX;
                wmParams.y += mTouchCurrentY - mTouchStartY;
                mWindowManager.updateViewLayout(mFloatLayout, wmParams);

                mTouchStartX = mTouchCurrentX;
                mTouchStartY = mTouchCurrentY;
                break;
            case MotionEvent.ACTION_UP:
            case MotionEvent.ACTION_CANCEL:

                mStopX = wmParams.x;//(int)event.getX();
                mStopY = wmParams.y;//(int)event.getY();
                if (Math.abs(mStartX - mStopX) >= 5 || Math.abs(mStartY - mStopY) >= 5) {
                    isMove = true;
                }

                break;
        }

        return mGestureDetector.onTouchEvent(event) || isMove;
    }

    //开始触控的坐标，移动时的坐标（相对于屏幕左上角的坐标）
    private int mTouchStartX, mTouchStartY, mTouchCurrentX, mTouchCurrentY;
    //开始时的坐标和结束时的坐标（相对于自身控件的坐标）
    private int mStartX, mStartY, mStopX, mStopY;
    private boolean isMove;//判断悬浮窗是否移动

    /**
     * http://www.cnblogs.com/tianzhijiexian/p/3994546.html
     *
     * @author:金凯
     * @tips :自己定义的手势监听类
     * @date :2014-3-29
     */
    class MyOnGestureListener extends GestureDetector.SimpleOnGestureListener {
        @Override
        public boolean onSingleTapConfirmed(MotionEvent e) {
//            if (!isMove) {
//                Toast.makeText(getApplicationContext(), "你点击了悬浮窗", Toast.LENGTH_SHORT).show();
//            }
            return super.onSingleTapConfirmed(e);
        }

    }


}
